import Taro, { Component } from '@tarojs/taro'
import { Swiper, SwiperItem, Image, View, Text,ScrollView } from '@tarojs/components'
import '../../assets/common.scss'
import CommonJs from '../../utils/common'
import Hearder from '../index/hearder'
import Gwlist from '../index/gwlist'
import ChatCarousel from '../chat/chatcarousel'
import './activity.scss' 

export default class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      result:[],
      qun_date:'',
      navindex:0,//用于判断导航选中
      pageheight:0,//获取高度
      qid:"",
      pageNumber:0,//页码数
      scrollPd:false,//是否可滑动
      hasNextPage:false,//是否有下一页
      znwns:'',
      mytime:null,
      updatete:true,
      iszy:0,
      registerCredit:0,
      showgw:0,//15秒后显示顾问小按钮
      gwinfo:""
    }
  }
  config = {
    navigationBarTitleText: '加载中'
  }
	componentDidShow () {
		var _this=this;
		var dateinfo=Taro.getStorageSync('dateinfo')
		if(dateinfo.qid){
			var cid=dateinfo.qid;
			_this.getgroup(cid)
	    _this.getquninfo(cid)
      _this.setState({
          result:[]
      })
	    _this.getactivity(0,cid)
		}
  }
  componentWillMount () {
    var _this = this
    var par = _this.$router.params
    //console.log(par+"///sdddsss");
    var cid=par.scene
 
    if (!cid) {
      CommonJs.open('/pages/grouplist/grouplist')
    } 
    else 
    {
 
			if(cid.indexOf("cccccc")>=0){
				/*微信公众号推送消息后点击进入小程序顾问聊天，来路/pages/activity/activity?scene=qid+'cccccc'+friendId+"cccccc"+name*/
				var arr=cid.split("cccccc");
				var consultant={
					id:arr[1],
					accountName:arr[2]
				}
				var gwinfo={
					consultant:consultant
				}
	  		this.setState({
	        gwinfo:gwinfo,
	        qid:arr[0]
	      })
	  		setTimeout(function(){
	  			_this.chat()
	  		},600)
	  		cid=arr[0];
	  		var dateinfo = Taro.getStorageSync('dateinfo')
		    dateinfo.qid = cid
		    Taro.setStorage({key:'dateinfo',data:dateinfo})
			}
			else if(cid.indexOf("aa")>=0){
				/*微信朋友圈分享二维码入口 二维码内容格式 pages/activity/activity?scene=957aa152aa430 */
				//console.log(cid+"///ewseee")
				var arr=cid.split("aa");
				var dateinfo = Taro.getStorageSync('dateinfo')
		    dateinfo.qid = arr[0] 
		    dateinfo.introducer = arr[2]
		    Taro.setStorage({key:'dateinfo',data:dateinfo})
		    if(arr[1]!='qun'){
		    	/*群分享不用跳转*/
		    	this.opendetails("/pages/activitydetails/activitydetails",arr[1])
		    }
			}
			else{
				 _this.setState({
		      qid: cid
		    })
		    var dateinfo = Taro.getStorageSync('dateinfo')
		    dateinfo.qid = cid
		   
		    Taro.setStorage({key:'dateinfo',data:dateinfo})
	      _this.getgroup(cid)
		    _this.getquninfo(cid)
		    _this.getactivity(0,cid)
		    var dateinfo=Taro.getStorageSync('dateinfo')
		    if(dateinfo){
					if(dateinfo.token){
						
						_this.getiszy();
		    		CommonJs.getFootPrint('COME',1,dateinfo.qid);
					}
				}
		  }
			
    }
	  
  }

  padntoz(){
    var _this=this
    var par = _this.$router.params
    if (par.shareUid) {
      _this.$preload({
        shareUid: par.shareUid
      })
      CommonJs.openTo('/pages/pkgo/invitespk')
    }  
    else if (par.activityId) {
    	if(par.introducer){
    		var dateinfo = Taro.getStorageSync('dateinfo')
		    dateinfo.qid = par.activityId
		    dateinfo.introducer = par.introducer
		    Taro.setStorage({key:'dateinfo',data:dateinfo})
    	}
      _this.$preload({
        activityId: par.activityId
      })
      CommonJs.openTo('/pages/activitydetails/activitydetails')
    }
  }
  componentWillUnmount () {
    clearTimeout(this.mytime)
    var dateinfo=Taro.getStorageSync('dateinfo')
    if(dateinfo){
			if(dateinfo.token){
				CommonJs.getFootPrint('GO',1,dateinfo.qid);
			}
		}
  }
  componentDidUpdate(){
    var _this = this
    var updatete = _this.state.updatete
    if (updatete) {
      _this.setState({
        updatete:false
      })
      setTimeout(() => { _this.padntoz() }, 600)
    }
  }
  getgroup(cid){
    //加群接口
    var _this=this
    var date={
      clusterId:cid
    }
    CommonJs.ajaxRequest('/openClusterBindingUser/create',date,'GET',function(res){
    },'noloading','noret')
  }
  getactivity(pageNumber,cid){
    //获取活动列表
    // console.log(pageNumber+'pageNumber1')
    
    var _this=this;
    var url='/verify/papi/v1.9/project/page/distanceTime?page='+pageNumber+"&culsterId="+cid;
    CommonJs.ajaxRequest(url,'','GET',function(res){
      	if(res.data.page<res.data.totalPages){
					var hasNextPage = true
				} 
				else{
					var hasNextPage = false
				}
				if(pageNumber==0){
					var results = [];
				}
				else{
	      	var results = _this.state.result
	     }
	      var result = res.data.list;
	      for(var i = 0; i < result.length; i++){
	        results.push(result[i])
	      }
	      if (hasNextPage) {
	        _this.setState({
	          result:results,
	          znwns: '暂无活动',
	          pageNumber: res.data.page,
	          hasNextPage: hasNextPage,
	          scrollPd: true
	        })
	      }
		    else {
	        _this.setState({
	          result:results,
	          znwns: '暂无活动',
	          pageNumber: res.data.page,
	          hasNextPage: hasNextPage,
	          scrollPd: false
	        })
	      }
		
		})
    
  }
  loadMore(){
    var _this = this;
    var pd = _this.state.scrollPd;
    if(pd) {
      //防止多次触发滑动到底部事件
      _this.setState({
        scrollPd: false//禁止下拉
      })
      var pageNumber = _this.state.pageNumber + 1;
      _this.getactivity(pageNumber,_this.state.qid);
    }else{
      var hasNextPage =  _this.state.hasNextPage;
      if(hasNextPage){
        Taro.showToast({
            title:'正在加载数据...',
            icon: 'none',
            duration: 2000
          });
      }else{
        Taro.showToast({
            title:'没有更多数据啦！',
            icon: 'none',
            duration: 2000
          });
      }
    }
  }
  
  open(url,type){
    this.$preload({
      type:type
    })
    CommonJs.openTo(url);
  }
  opens(url,type){
    this.$preload({
      type:type
    })
    CommonJs.open(url);
  }
  opendetails(url,id){
    this.$preload('activityId',id);
    CommonJs.openTo(url);
  }
  getquninfo(cid){
    var _this=this
    var date1={id:cid}
    CommonJs.ajaxRequest('/cluster/getEntityAndLoginId',date1,'GET',function(res){
      Taro.setNavigationBarTitle({title:res.content.name})
      var wh=0;
        Taro.getSystemInfo({
          success:function(res){
          	wh=res.windowHeight;
          }   
        })
        var query=Taro.createSelectorQuery()
        query.select('.qun-bgbanner').boundingClientRect(function(rect){
          //console.log(wh+"//"+rect.height+"//ssssss")
          _this.setState({
              qun_date: res.content,
              pageheight:wh-rect.height
          })
        }).exec();
    })
  }
         
  getiszy(){
  	var _this=this;
  	CommonJs.ajaxRequest('/guide/createGuide','','GET',function(res){
  		if(res.content.type==2||res.content.type==3){
	  		_this.setState({
		      iszy: 1,
		      registerCredit:res.content.registerCredit
		    })
	    }
  		else{
  			_this.guide(0);
  		}
  	})
  }
  guide(val){
  	this.setState({
      iszy: val
    })
  	Taro.setStorage({key:'guide',data:val})
  	
  }
  closezy(){
  	if(this.state.iszy>0){
  		CommonJs.ajaxRequest('/guide/updateGuide','','GET',function(res){})
  		this.guide(0);
  	}
  }
  onShareAppMessage(res){
  	var dateinfo = Taro.getStorageSync('dateinfo');
    if(dateinfo.userid){
    	var uid=dateinfo.userid;
    }
    else{
    	var uid=0;
    }
    let title = '"'+this.state.qun_date.name+'社群"，点击进入，和我一起参加活动吧'
    let path = '/pages/activity/activity?scene='+this.state.qun_date.id+'aaqunaa'+uid
    let imageUrl = this.state.qun_date.photo
    return CommonJs.onShareAppMessage(title, path, imageUrl)
  }
 
  render () {
    const result = this.state.result
    const list_date = this.state.qun_date
    
    return (
      <View className='page footpage'>
      	<official-account style="width:100%;height:80px;border:none;"></official-account>
      	<View className='focusgzh'>关注公众号可以快速获取优惠券信息哟</View>
        <View className='qun-bgbanner'>
          <Hearder propItem={list_date} porpNav={this.state.navindex} propGuite={this.state.iszy} onHandOpen={this.opens.bind(this)}></Hearder>
        </View>
        <ScrollView className='qun-activity' scrollY='true' style={'height:'+this.pageheight+'px'} onScrollToLower={this.loadMore.bind(this,'')}>
          <View className='qun-znwn' style={result.length!=0?'display:none':'display:block;'}>{this.state.znwns}</View>
          {result.map((item, index) => (
          <View className='qun-hodo'>
            <View className='qun-hodos' onClick={this.opendetails.bind(this,'/pages/activitydetails/activitydetails',item.id)}>
              {item.projectStatus ? 
                ""
                :
                <View className='qun-hdstop'><Image mode='scaleToFill' className='ban-hodoimgs' src='https://minichat.g2ma.com/kedouimg/huodstop.png'></Image></View>
              }
              <View className='ban-hodoimgwa'>
                <Image mode='scaleToFill' className='ban-hodoimg' src={item.logo}></Image>
              </View>
              <View className='qun-list-nr'>
	              <View className='qun-hdmc'>{item.name}</View>
	              <View className='qun-hdinfo'>
	                <View className='qun-dizi'>
	                  
	                  <Text decode='true' className='qun-hddz'>{item.cityName}{item.areaName}{item.districtName}{item.activityAddress}</Text>
	                </View>
	              </View>
	              <View className='qun-rs'>
	                <Text className='qun-money'>{item.basePrice/100}</Text>元起
	                <Text className='qun-bmnum'>已有{item.saleCount}人参加</Text>
	              </View>
	            </View>
	            <Text decode='true' className='qun-hddjs'>剩余{CommonJs.countDowns(item.finishLong*1000,item.finishLong*2000,1)}</Text>
            </View>
          </View>
          ))}
            
        </ScrollView>
        <View className='bg' style={this.state.iszy>=1?'display:block':'display:none;'}></View> 
        <View className='ydcon' style={this.state.iszy==2?'display:block;top:40%':'display:none;'}>
        	<Image className='jt' mode='widthFix' src='https://minichat.g2ma.com/kedouimg/jt.png'></Image>
        	<Text className='ydcon-text'>点击抽奖,进入抽奖界面</Text>
        	<View className='ydcancle' onClick={this.closezy}>退出新手指引</View>
        </View>
        <View className='ydconkq' style={this.state.iszy==1?'display:block':'display:none;'}>
            <Text className='ydcon-text'>欢迎来到{CommonJs.getname()}!</Text>
        	<Text className='ydcon-text'>恭喜您,获得{this.state.registerCredit}积分</Text>
        	<Text className='ydcon-text'>一起来体验一下吧</Text>
        	<View className='ydcancle' onClick={this.guide.bind(this,2)}>开启体验历程</View>
        </View>
      </View>
    )
  }
}

 